package com.ktjiaoyu.crm.service;

import com.ktjiaoyu.crm.entity.User;
import com.ktjiaoyu.crm.repository.UserRepository;
import org.junit.Test;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class UserServiceImpl implements UserService {
    @Resource
    private UserRepository userRepository;

    @Override
    public Page<User> findPageByMap(Map param, Pageable pageable) {
        return userRepository.findAll(new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (param.get("usrName") != null) { //动态SQL
                    predicates.add(cb.like(root.get("usrName"), "%" + param.get("usrName") + "%"));
                }
                if (param.get("roleId") != null) {
                    predicates.add(cb.equal(root.get("usrRoleId"), param.get("roleId")));
                }
                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        }, pageable);
    }

    @Test
    public void testFindPageByMap() {
        int page = 0, size = 2;//分页要素
        //控制分页数据的排序，可以选择升序和降序
//        Sort sort = new Sort(Sort.Direction.DESC, "usrId");
//        //控制分页的辅助类，可以设置页码、每页的数据条数、排序等
//        Pageable pageable = PageRequest.of(page, size, sort);
//        Map param = new HashMap();
//        param.put("roleId", 8L); //测试一个查询条件，也可不给或给多个
//        UserServiceImpl userService = null;
//        Page<User> userPager = userService.findPageByMap(param, pageable);
//        System.out.println("总记录数 --------> " + userPager.getTotalElements());
//        System.out.println("总页数 ----------> " + userPager.getTotalPages());
//        System.out.println("当前页数 --------> " + userPager.getNumber());
//        System.out.println("每页记录数 ------> " + userPager.getSize());
//        System.out.println("当前记录： ------> ");
//        for (User user : userPager.getContent()) {//获得查询记录
//            System.out.println("usrId：" + user.getUsrId());
//        }
    }
    }



